<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      title="请选择打印模板"
      width="500px"
      :footer="null"
      :visible.sync="visible"
    >
      <el-form :model="form" label-width="100px" class="modalForm">
        <el-form-item
          label="标签类型："
          v-show="!isContinu"
        >{{ mdl.lableType === 1 ? '普通RFID标签' : 'RFID抗金属标签' }}</el-form-item>
        <el-form-item label="打印模板：">
          <el-select clearable v-model="print" style="width: 100%">
            <el-option
              :value="item.templateId"
              :label="item.templateName"
              :key="index"
              v-for="(item,index) in templateData"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="IP地址：">
          <el-input placeholder="输入ip地址，本机可不填" v-model="ip" />
        </el-form-item>
        <el-form-item label="端口号：">
          <el-input placeholder="输入端口号，本机可不填" :readOnly="true" v-model="port" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="handlePrint" :disabled="print === null" type="primary">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTemplate, printLog } from '@/api/assetsNew'

export default {
  data() {
    return {
      print: null,
      ip: null,
      port: null,
      templateData: [],
      form: {},
      visible: false,
      mdl: {},
      wsocket: null,
      ip: '127.0.0.1', // 默认ip地址
      port: 1808,
      data: {},
      isContinu: false,
      recordsArr: [],
      receiveMsg: null
    }
  },
  methods: {
    async handlePrint() {
      const index = this.templateData.findIndex(v => v.templateId === this.print)
      this.data = JSON.parse(this.templateData[index].templateContent)
      // this.connection()
      // if (this.wsocket.readyState === 1) {
      console.log('打印类型', this.isContinu)

      if (this.isContinu) {
        // 连续打印
        this.recordsArr.map(async (v, i) => {
          if (i !== 0) {
            // 不是第一次则需监听回调的值
            // this.$message.success(this.receiveMsg)
            // this.$message.success(typeof this.receiveMsg)
            // console.log('v', v, i)
            setTimeout(async () => {
              // if (this.receiveMsg == 0) {
              console.log('v', v, v.assetsId, i)

              this.$emit('showMask', i, this.recordsArr.length)
              const res = await printLog({ assetsId: v.assetsId })

              // 等于0连续打印
              this.sendMessage(v)
              // } else {
              // this.$emit('hideMask')
              // 否则中断循环
              // return false
              // }
            }, (i + 1) * 10000)
          } else {
            this.$emit('showMask', i, this.recordsArr.length)
            this.sendMessage(v)
            const res = await printLog({ assetsId: v.assetsId })
          }
        })
      } else {
        //单个打印
        this.sendMessage(this.mdl)
        const res = await printLog({ assetsId: this.mdl.assetsId })
      }
    },
    async edit(record) {
      console.log('record', record, Array.isArray(record))
      this.isContinu = Array.isArray(record) ? true : false // 判断是否连续打印
      const res = await getTemplate({ templateType: record.lableType })
      this.templateData = res.data
      if (this.isContinu) {
        this.recordsArr = [...record]
      } else {
        this.mdl = Object.assign({}, record)
      }
      this.visible = true
      this.connection()
      // console.log('websocket 状态', this.wsocket.readyState)
    },
    strToHexCharCode(str) {
      if (str === '') return ''
      var hexCharCode = []
      for (var i = 0; i < str.length; i++) {
        hexCharCode.push(str.charCodeAt(i).toString(16))
      }
      return hexCharCode.join('')
    },
    buildData(data, assetsCode, assetsName, specification, brand) {
      data.assetsCode = data.assetsCode + assetsCode
      data.assetsName = data.assetsName + assetsName
      data.rfid = data.rfid + this.strToHexCharCode(assetsCode)
      data.qr = data.qr + this.strToHexCharCode(assetsCode)
      data.specification = data.specification + specification
      data.brand = data.brand + brand
      return data
    },
    connection() {
      var wsserver = 'ws://' + this.ip + ':' + this.port + '/'
      if ('WebSocket' in window) {
        this.wsocket = new WebSocket(wsserver)
      } else if ('MozWebSocket' in window) {
        this.wsocket = new MozWebSocket(wsserver)
      } else {
        alert('不支持当前浏览器！')
      }
      //注册各类回调
      this.wsocket.onopen = function() {
        console.log('已链接')
        // document.getElementById('status').value = '连接打印后台成功！'
        //this.wsocket.send('我是客户端，我准备好了。'); //给服务器发送消息
      }
      this.wsocket.onclose = function(event) {
        console.log('断开链接')
        // document.getElementById('status').value = '与打印后台断开连接！'
      }
      this.wsocket.onerror = function() //出错的提示
      {
        console.log('出错')
        //alert('数据传输错误！');
      }
      this.wsocket.onmessage = function(receiveMsg) {
        console.log('新消息', receiveMsg)
        this.receiveMsg = receiveMsg
        // document.getElementById('status').value = receiveMsg.data //显示服务器传回的消息
      }
    },
    //向打印后台发送消息
    sendMessage(row = {}) {
      const { assetsCode, assetsName, specification, brand } = row
      const data = this.buildData(this.data, assetsCode, assetsName, specification, brand)
      this.wsocket.send('OpenPort|255') //打开端口
      this.wsocket.send('ZM_ClearBuffer') //清空
      this.wsocket.send('ZM_SetPrintSpeed|40') //设置速度
      this.wsocket.send('ZM_SetDarkness|15') //设置黑度
      this.wsocket.send(data.height) //设置标签高度和间隙
      this.wsocket.send(data.width) //设置标签宽度
      if (data.qr) {
        this.wsocket.send(data.qr) //打印QR二维条码
      }
      if (data.assetsName) {
        this.wsocket.send(data.assetsName) //打印文字
      }
      if (data.assetsCode) {
        this.wsocket.send(data.assetsCode) //打印文字
      }
      if (data.specification) {
        this.wsocket.send(data.specification) //打印文字
      }
      if (data.brand) {
        this.wsocket.send(data.brand) //打印文字
      }
      if (data.line) {
        data.line.forEach((element, index) => {
          this.wsocket.send(element) //画直线
        })
      }
      if (data.rfid) {
        this.wsocket.send(data.rfid) //写入RFID数据
      }

      //this.wsocket.send('ZM_HF_RfidFormat|2|1|1|0');//设置RFID HF
      //this.wsocket.send('ZM_HF_RW_RfidData|2|1|2|1122334455667788');//写入RFID数据
      //this.wsocket.send('ZM_DrawHFRFID_UID|10|10|0|2|1|2|2|78|0|R');//获取HF UID，不打印在标签
      this.wsocket.send('ZM_PrintLabel|1|1') //打印标签
      //this.wsocket.send('ZM_GetHfRfidUID_UsbEx|255|0|3000');//读出UID
      this.wsocket.send('ClosePort') //关闭端口
    }
  }
}
</script>

<style scoped>
.modalForm >>> .el-form-item {
  margin-bottom: 10px;
}
</style>